package com.jacobson.huobi.mvp

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSONObject
import com.google.android.material.tabs.TabLayout
import com.jacobson.core.base.Immersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.framework.delegation.WeakRef
import com.jacobson.core.mvp.BaseMvpActivity
import com.jacobson.core.mvp.IPresenter
import com.jacobson.core.utils.ImmersiveExtensions
import com.jacobson.huobi.Constants
import com.jacobson.huobi.HuobiApplication
import com.jacobson.huobi.R
import com.jacobson.huobi.common.BaseSelectableFragment
import com.jacobson.huobi.di.components.DaggerAboutCeluerenActivityComponent
import com.jacobson.huobi.di.components.DaggerEditPasswordActivityComponent
import com.jacobson.huobi.di.components.DaggerRenevalMemberActivityComponent
import com.jacobson.huobi.di.modules.AboutCeluerenActivityModule
import com.jacobson.huobi.di.modules.EditPasswordActivityModule
import com.jacobson.huobi.di.modules.RenevalMemberActivityModule
import com.jacobson.huobi.entities.events.VipRechargeEvent
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.vo.RechargeRecordVo
import com.jacobson.huobi.mvp.adapters.ReChargeRecordAdapter
import com.jacobson.huobi.mvp.contract.AboutCeluerenContract
import com.jacobson.huobi.mvp.contract.EditPasswordContract
import com.jacobson.huobi.mvp.contract.RenevalMemberContract
import com.jacobson.huobi.mvp.fragment.HomeFragment
import com.jacobson.huobi.mvp.fragment.MeFragment
import com.jacobson.huobi.mvp.fragment.SymbolFragment
import com.jacobson.huobi.mvp.fragment.VipFragment
import com.jacobson.huobi.utils.ResourcesUtil
import kotlinx.android.synthetic.main.activity_contact_us.*
import kotlinx.android.synthetic.main.activity_contact_us.tvContactUsQQGroup
import kotlinx.android.synthetic.main.activity_edit_password.*
import kotlinx.android.synthetic.main.activity_edit_password.btnBack
import kotlinx.android.synthetic.main.activity_reneval_member.*
import kotlinx.android.synthetic.main.fragment_currency.*
import kotlinx.android.synthetic.main.fragment_vip.*
import kotlinx.android.synthetic.main.item_vip_tab.view.*
import org.simple.eventbus.EventBus
import javax.inject.Inject

@Immersive(fitSystemWindows = false)
class RenevalMemberActivity :
    BaseMvpActivity<RenevalMemberContract.Presenter>(), RenevalMemberContract.View {

    @field:Inject
    lateinit var reChargeRecordAdapter: ReChargeRecordAdapter

    //是否显示记录
    private var isShowRecord = true

    //刷新页
    private var page = 0



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //修改底部功能键背景色 只支持api为21及以上
        if (Build.VERSION.SDK_INT  >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = ResourcesUtil.getColor(R.color.colorPrimary) //设定底部导航栏  同全局颜色
        }
    }
    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerRenevalMemberActivityComponent.builder()
            .renevalMemberActivityModule(RenevalMemberActivityModule(this))
            .appComponent(appComponent)
            .activityModule(ActivityModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.activity_reneval_member

    override fun initData(savedInstanceState: Bundle?) {
        initBtnClick()
        initTabFrame()

        with(rechargeRecordRecyclerView) {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(com.jacobson.huobi.components.SpaceItemDecoration(3f))
            adapter = reChargeRecordAdapter
        }

        with(smartRechargeRecordRefreshLayout) {
            setOnRefreshListener {
                page--
                if (page < 0) {
                    page = 0
                }
                loadVipRecordList(page)
            }
            setOnLoadMoreListener {
                page++
                loadVipRecordList(page)
            }
        }

    }

    private fun loadVipRecordList(page: Int) {
        presenter.loadVipRecord(page)
    }

    /**
     * 充值记录响应
     */
    override fun onLoadVipRecordResp(response: CommonResponse<List<RechargeRecordVo>>) {
        smartRechargeRecordRefreshLayout.finishLoadMore()
        smartRechargeRecordRefreshLayout.finishRefresh()
        if (response.code == Constants.RESP_OK) {
            if (response.data.isEmpty()) {
                page--
            }else {
                reChargeRecordAdapter.update(response.data)
            }
        }
    }

    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
//        smartRechargeRecordRefreshLayout.finishLoadMore()
//        smartRechargeRecordRefreshLayout.finishRefresh()
        logger.e("error >>> $message")
        return super.onError(type, extra, code, message)
    }

    /**
     * 初始化按钮
     */
    private fun initBtnClick() {
        btnBack.setOnClickListener {
            this.finish()
        }

        btnSwitchRechargeAndRecord.setOnClickListener {
            isShowRecord = !isShowRecord
            if (isShowRecord) {
                btnSwitchRechargeAndRecord.text = "充值记录"
                llVipRechargeFragment.visibility = View.VISIBLE
                smartRechargeRecordRefreshLayout.visibility = View.GONE
            }else {
                btnSwitchRechargeAndRecord.text = "充值列表"
                llVipRechargeFragment.visibility = View.GONE
                smartRechargeRecordRefreshLayout.visibility = View.VISIBLE
                loadVipRecordList(0)
            }
        }
    }

    private fun showTab(position: Int) {
        vipTabLayout.getTabAt(position)?.select()
        logger.d("MainActivity: ShowTab = $position")
    }

    @SuppressLint("InflateParams")
    private fun initTabFrame() {

        for (position in TAB_NAME_IDS.indices) {
            val newTab = vipTabLayout.newTab()
            newTab.customView = obtainTabItemView(position)
            vipTabLayout.addTab(newTab)
        }

        vipTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
                setTabItemTabSelectedState(tab, true)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                setTabItemTabSelectedState(tab, false)
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                setTabItemTabSelectedState(tab, true)
                val position = tab?.position ?: 0
                showCurrentFragment(position)
            }

        })

        supportFragmentManager.beginTransaction()
            .add(R.id.vipTabLiveFragmentContainer, fetchFragment())
            .hide(fetchFragment())
            .commit()
        showTab(0)
        showCurrentFragment(0)

    }

    private var lastContainer: BaseSelectableFragment<*> = VipFragment.newInstance()

    private fun showCurrentFragment(position: Int) {
        supportFragmentManager.beginTransaction()
            .show(fetchFragment())
            .commit()
        lastContainer.unSelect()
        lastContainer = fetchFragment()
        lastContainer.select()
        ImmersiveExtensions.immersive(lastContainer)
        EventBus.getDefault().post(VipRechargeEvent(true, position + 4))
//        tvMainNetworkStatus.text = "1111"
//        tvMainShowNetworkStatus.bringToFront()
    }



    @SuppressLint("InflateParams")
    private fun obtainTabItemView(position: Int): View {
        val inflater = LayoutInflater.from(this)
        val tabView = inflater.inflate(R.layout.item_vip_tab, null, false)
        tabView.vipTabName.text = TAB_NAME_IDS[position]
        return tabView
    }

    private fun setTabItemTabSelectedState(tab: TabLayout.Tab?, isSelected: Boolean) {
        logger.d("setTabItemTabSelectedState: ${tab?.text}, $isSelected ${tab?.position}")
        tab?.customView?.vipTabName?.let {
            if (isSelected != it.isSelected) {
                it.isSelected = isSelected
//                it.setBackgroundResource(R.drawable.ic_vip_recharge_tab_item_selected)
            }
        }
    }
    companion object {
        internal val TAB_NAME_IDS =
            HuobiApplication.getInstance().resources.getStringArray(R.array.arr_vip_tab_value)

        const val POSITION_SYMBOL_PRIMARY: Int = 0
        const val POSITION_SYMBOL_VIP: Int = 1
        const val POSITION_SYMBOL_PLATINUM: Int = 2

        @Synchronized
        private fun fetchFragment(): BaseSelectableFragment<out IPresenter> {
            return VipFragment.newInstance()
        }

        fun startActivity(context: Context) {
            Intent(context, RenevalMemberActivity::class.java).run {
                context.startActivity(this)
            }
        }

    }

}
